package com.cqq.auth.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cqq.auth.constant.AuthMessage;
import com.cqq.auth.dao.OrganizationDao;
import com.cqq.auth.dao.domain.Organization;
import com.cqq.auth.service.OrganizationService;
import com.cqq.auth.service.bean.OrganizationBean;
import com.cqq.auth.service.bean.OrganizationQueryBean;
import com.cqq.auth.service.exception.OrganizationServiceException;
import com.cqq.common.core.base.BaseService;
import com.cqq.common.core.constant.CommonMessage;
import com.cqq.common.core.util.BeanUtil;

@Service("organizationService")
public class OrganizationServiceImpl extends BaseService implements OrganizationService {

	private static final Logger log = LoggerFactory.getLogger(OrganizationServiceImpl.class);
	
	@Autowired
	private OrganizationDao organizationDao;

	
	public OrganizationBean addOrganization(OrganizationBean org)
			throws OrganizationServiceException {
		log.debug("addOrganization ...");
		if(org==null || StringUtils.isBlank(org.getName())
				|| org.getParentId()==null){
			throw super.buildException(new OrganizationServiceException(CommonMessage.COMMON_PARAM_EMPTY));
		}
		
		Organization o = this.organizationDao.queryByNameAndParentId(org.getName(), org.getParentId());
		if(o != null){
			throw super.buildException(new OrganizationServiceException(AuthMessage.ORG_NAME_DUPLICATE));
		}
		
		o=new Organization();
		BeanUtil.copy(org, o);
		this.organizationDao.add(o);
		org.setId(o.getId());
		log.debug("addOrganization ok! {}",org);
		return org;
	}

	
	public void updateOrganization(OrganizationBean org)
			throws OrganizationServiceException {
		log.debug("updateOrganization ...");
		if(org==null || org.getId()==null
				|| StringUtils.isBlank(org.getName())
				|| org.getParentId()==null){
			throw super.buildException(new OrganizationServiceException(CommonMessage.COMMON_PARAM_EMPTY));
		}
		
		Organization o = this.organizationDao.queryByNameAndParentId(org.getName(), org.getParentId());
		if(o != null && !o.getId().equals(org.getId())){
			throw super.buildException(new OrganizationServiceException(AuthMessage.ORG_NAME_DUPLICATE));
		}
		
		o=new Organization();
		BeanUtil.copy(org, o);
		if(this.organizationDao.update(o)!=1){
			throw super.buildException(new OrganizationServiceException(CommonMessage.COMMON_UPDATE_ERROR));
		}
		log.debug("updateOrganization ok! {}",org);
	}

	
	public List<OrganizationBean> listOrganization(Integer[] ids) {
		List<Organization> orgs=this.organizationDao.queryByIds(ids);
		List<OrganizationBean> beans=BeanUtil.copyList(orgs, OrganizationBean.class);
		return beans;
	}

	
	public List<OrganizationBean> listOrganizationByParentId(Integer parentId) {
		List<Organization> orgs=this.organizationDao.queryByParentId(parentId);
		List<OrganizationBean> beans=BeanUtil.copyList(orgs, OrganizationBean.class);
		return beans;
	}

	
	public void deleteOrganization(Integer id)
			throws OrganizationServiceException {
		log.debug("deleteOrganization ...");
		if(id==null){
			throw super.buildException(new OrganizationServiceException(CommonMessage.COMMON_PARAM_EMPTY));
		}
		Organization org=this.organizationDao.queryById(id);
		if(org==null){
			throw super.buildException(new OrganizationServiceException(AuthMessage.ORG_NOT_EXIST));
		}
		this.organizationDao.deleteAll(id);
		log.debug("deleteOrganization ok! id:{}",id);
	}

	
	public OrganizationBean findOrganization(Integer id) {
		if(id==null){
			return null;
		}
		Organization org=this.organizationDao.queryById(id);
		if(org==null){
			return null;
		}
		OrganizationBean bean=new OrganizationBean();
		BeanUtil.copy(org, bean);
		return bean;
	}

	/**
	 * 查询子组织，返回结果带父组织
	 */
	
	public List<OrganizationBean> listOrganizationByName(String name,Integer parentId) {
		if(parentId==null){
			return null;
		}
		List<Organization> orgs=this.organizationDao.queryByName(name,parentId);
		List<OrganizationBean> beans=BeanUtil.copyList(orgs, OrganizationBean.class);
		return beans;
	}

	
	public List<OrganizationBean> listOrganizationByUser(Integer userId) {
		if(userId==null){
			return null;
		}
		List<Organization> orgs=this.organizationDao.queryByUserId(userId);
		List<OrganizationBean> beans=BeanUtil.copyList(orgs, OrganizationBean.class);
		return beans;
	}
	
	
	public List<OrganizationBean> listOrganizationByUser(Integer userId,Integer parentId) {
		if(userId==null){
			return null;
		}
		List<Organization> orgs=this.organizationDao.queryByUserId(userId);
		List<OrganizationBean> list=null;
		if(parentId!=null){
			Map<Integer, Integer> map=countUserByParentId(parentId);
			list=new ArrayList<OrganizationBean>();
			if(orgs!=null&&orgs.size()>0){
				for (Organization org : orgs) {
					if(map.get(org.getId())!=null){
						OrganizationBean bean=new OrganizationBean();
						BeanUtil.copy(org, bean);
						list.add(bean);
					}
				}
			}
		}else{
			list=BeanUtil.copyList(orgs, OrganizationBean.class);
		}
		return list;
		
	}

	
	public Map<Integer, Integer> countUserByParentId(Integer parentId) {
		Map<Integer,Integer> result=new HashMap<Integer,Integer>();
		try {
			if(parentId==null){
				return null;
			}
			List<Map<String,Integer>> lt=this.organizationDao.listUserCountByParentId(parentId);
			int allCount=0;
			if(lt!=null){
				for(Map<String,Integer> map:lt){
					result.put(map.get("id").intValue(), Integer.valueOf(map.get("count")+""));
					allCount=allCount+Integer.valueOf(map.get("count")+"").intValue();
				}
			}
			result.put(parentId, allCount);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	
	public List<OrganizationBean> listChildrenOrgByName(String name,
			Integer parentId) {
		// TODO Auto-generated method stub
		if(name==null||parentId==null){
			return null;
		}
		List<Organization> orgs=organizationDao.queryChildrenOrgByName(name, parentId);
		List<OrganizationBean> beans=BeanUtil.copyList(orgs, OrganizationBean.class);
		return beans;
	}

	
	public List<OrganizationBean> queryOrgByParentId(
			OrganizationQueryBean queryBean) {
		// TODO Auto-generated method stub
		Organization org=new Organization();
		BeanUtil.copy(queryBean, org);
		List<Organization> list=organizationDao.queryOrgByParentId(org);
		return BeanUtil.copyList(list, OrganizationBean.class);
	}

}
